package com.lam.common.pay.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.lam.common.exception.BusinessException;
import com.lam.common.pay.config.AlipayConfig;
import com.lam.common.pay.vo.UnifiedOrderVo;
import com.lam.common.utils.JsonUtil;

@Service
public class LamAlipayService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public UnifiedOrderVo createAlipayH5Order(String payNo, BigDecimal totalAmount, String orderDesc, String orderNos) {

		try {
			// https://opendoc.alipay.com/open/02ivbs?scene=21&pathHash=0a6313c7
			// 获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.me().getGatewayUrl(), AlipayConfig.me().getAppId(),
					AlipayConfig.me().getMerchantPrivateKey(), AlipayConfig.me().getFormat(), AlipayConfig.me().getCharset(),
					AlipayConfig.me().getAlipayPublicKey(), AlipayConfig.me().getSignType());

			AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
			request.setReturnUrl(AlipayConfig.me().getReturnUrl());
			request.setNotifyUrl(AlipayConfig.me().getNotifyUrl());
			Map<String, Object> bizContentData = new HashMap<>();
			bizContentData.put("out_trade_no", payNo);// 商户订单号，商户网站订单系统中唯一订单号，必填
			bizContentData.put("total_amount", totalAmount);// 付款金额，必填
			bizContentData.put("subject", orderDesc);// 订单名称，必填
			bizContentData.put("body", orderNos);// 商品描述，可空
//			bizContentData.put("product_code", "FAST_INSTANT_TRADE_PAY");// 手机网站支付默认传值FAST_INSTANT_TRADE_PAY, 可选
			bizContentData.put("product_code", "QUICK_WAP_WAY");
//			bizContent.put("time_expire", "2022-08-01 22:00:00");

			//// 商品明细信息，按需传入
			// JSONArray goodsDetail = new JSONArray();
			// JSONObject goods1 = new JSONObject();
			// goods1.put("goods_id", "goodsNo1");
			// goods1.put("goods_name", "子商品1");
			// goods1.put("quantity", 1);
			// goods1.put("price", 0.01);
			// goodsDetail.add(goods1);
			// bizContent.put("goods_detail", goodsDetail);

			//// 扩展信息，按需传入
			// JSONObject extendParams = new JSONObject();
			// extendParams.put("sys_service_provider_id", "2088511833207846");
			// bizContent.put("extend_params", extendParams);

			// 拼接参数
			request.setBizContent(JsonUtil.toJsonString(bizContentData));
			AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
			if (response.isSuccess()) {
				return new UnifiedOrderVo(response.getTradeNo(), response.getBody());
			} else {
				logger.error("支付宝H5支付生成订单失败， response：{}", JsonUtil.toJsonString(response));
				throw new BusinessException("订单支付失败！");
			}
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			logger.error("支付宝H5支付生成订单异常， payNo:"+payNo+", orderNos:"+orderNos, e);
			throw new BusinessException("订单支付失败！");
		}
	}
	
	public AlipayTradeQueryResponse queryTradeResult(String payNo, String tradeNo) {
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.me().getGatewayUrl(), AlipayConfig.me().getAppId(),
					AlipayConfig.me().getMerchantPrivateKey(), AlipayConfig.me().getFormat(), AlipayConfig.me().getCharset(),
					AlipayConfig.me().getAlipayPublicKey(), AlipayConfig.me().getSignType());
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
			JSONObject bizContent = new JSONObject();
			bizContent.put("out_trade_no", payNo);
			bizContent.put("trade_no", tradeNo);
			request.setBizContent(bizContent.toString());
			AlipayTradeQueryResponse response = alipayClient.execute(request);
			logger.info("支付宝H5支付结果查询，response：{}", JsonUtil.toJsonString(response));
			return response;
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			logger.error("支付宝H5支付结果查询异常， payNo:"+payNo+", tradeNo:"+tradeNo, e);
			throw new BusinessException("支付结果查询失败！");
		}
	}

}
